package com.factory.rest.config;


import com.factory.common.core.BaseException;
import com.factory.common.core.LoginException;
import com.factory.common.core.ServiceException;
import com.factory.common.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常拦截
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(HttpServletRequest request, Exception e) {

        if (e instanceof LoginException) {
            return Result.fail(null, e.getMessage(), ((LoginException) e).getCode());
        }

        log.error("异常拦截器拦截错误信息,{}", e);
        //绑定异常是需要明确提示给用户的
        if (e instanceof ServiceException) {
            return Result.fail(null, e.getMessage(), ((ServiceException) e).getCode());
        } else if (e instanceof BaseException) {
            return Result.fail(e, e.getMessage(), ((BaseException) e).getCode());
        } else if (e instanceof RuntimeException) {
            return Result.fail(e.getMessage(), "系统运行时错误", 500);
        }

        return Result.fail(e.getMessage(), "系统未知错误", 500);
    }

}
